{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "from pandas import DataFrame, Series\n",
    "import glob\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from sklearn.cluster import KMeans\n",
    "# from sklearn.metrics import silhouette_score\n",
    "\n",
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-11-07T02:59:06.321900400Z",
     "start_time": "2023-11-07T02:59:05.458914100Z"
    }
   },
   "id": "ac029c4afdce4dd9"
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "def strToList(row):\n",
    "    row['职位'] = eval(row[\"职位\"])\n",
    "    row['任职要求'] = eval(row[\"任职要求\"])\n",
    "    return row\n",
    "\n",
    "\n",
    "def runKmeans(data_frame: DataFrame):\n",
    "    # 降维 并去掉空列表\n",
    "    positions = data_frame[\"职位\"].explode().dropna().tolist()\n",
    "    requirements = data_frame[\"任职要求\"].explode().dropna().tolist()\n",
    "    \n",
    "    # 使用TF-IDF向量化文本数据\n",
    "    # 过滤出现概率大于85%的常用词 只要前2000的结果\n",
    "    # tfidf_vectorizer = TfidfVectorizer(max_df=0.85, max_features=2000)\n",
    "    tfidf_vectorizer = TfidfVectorizer()\n",
    "    position_tfidf = tfidf_vectorizer.fit_transform(positions)\n",
    "    requirements_tfidf = tfidf_vectorizer.fit_transform(requirements)\n",
    "\n",
    "    # 使用K-Means进行聚类\n",
    "    if len(positions) > 60:\n",
    "        position_n_clusters = 8\n",
    "    else:\n",
    "        position_n_clusters = 3\n",
    "    if len(requirements) > 200:\n",
    "        requirements_n_clusters = 10\n",
    "    else:\n",
    "        requirements_n_clusters = 8\n",
    "    position_kmeans = KMeans(n_clusters=position_n_clusters)\n",
    "    requirements_kmeans = KMeans(n_clusters=requirements_n_clusters)\n",
    "\n",
    "    # 聚类结果\n",
    "    position_clusters = position_kmeans.fit_predict(position_tfidf)\n",
    "    requirements_clusters = requirements_kmeans.fit_predict(requirements_tfidf)\n",
    "    \n",
    "    # 合并到一个dataframe对象中\n",
    "    title = Series(positions, name=\"职位\")\n",
    "    desc = Series(requirements, name=\"任职要求\")\n",
    "    title_clusters = Series(position_clusters, name=\"职位簇\")\n",
    "    desc_clusters = Series(requirements_clusters, name=\"任职要求簇\")\n",
    "    data_frame = pd.concat([title, title_clusters, desc, desc_clusters], axis=1)\n",
    "    # 输出职位和任职要求的聚类结果\n",
    "    return data_frame"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2023-11-07T02:59:06.365925700Z",
     "start_time": "2023-11-07T02:59:06.325906700Z"
    }
   },
   "id": "a9136872f67e3ceb"
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2023-11-07T02:59:21.496190400Z",
     "start_time": "2023-11-07T02:59:06.338959900Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "聚类结果 已保存到 ../Data/聚类/boss直聘.xlsx\n",
      "聚类结果 已保存到 ../Data/聚类/CareerBuilder.xlsx\n",
      "聚类结果 已保存到 ../Data/聚类/CIA.xlsx\n",
      "聚类结果 已保存到 ../Data/聚类/DNI.xlsx\n",
      "聚类结果 已保存到 ../Data/聚类/linkedin.xlsx\n",
      "聚类结果 已保存到 ../Data/聚类/Simplyhired.xlsx\n",
      "聚类结果 已保存到 ../Data/聚类/智联招聘.xlsx\n"
     ]
    }
   ],
   "source": [
    "files = glob.glob(\"../Data/语料库创建result/*\")\n",
    "\n",
    "path_ = \"../Data/聚类/\"\n",
    "if not os.path.exists(path_):\n",
    "    os.mkdir(path_)\n",
    "\n",
    "for file in files:\n",
    "    file_name = file.replace('\\\\', '/').split('/')[-1]\n",
    "    save_path = path_ + file_name \n",
    "    df = pd.read_excel(file)\n",
    "    # 删除重复行\n",
    "    df = df.drop_duplicates(keep='last')\n",
    "    # 去掉缺失值\n",
    "    df = df.dropna(subset=['职位', '任职要求'])\n",
    "    df.apply(func=strToList, axis=1)\n",
    "    df_ = runKmeans(df)\n",
    "    df_.to_excel(save_path)\n",
    "    print(\"聚类结果 已保存到\",save_path)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
